# -*- coding: utf-8 -*-

"""
调试商品页面底部的评论元素
"""

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
import time

def test_product_page_reviews():
    """
    测试商品页面底部的评论元素
    """
    print("开始测试商品页面底部的评论元素...")
    
    try:
        # 配置Chrome选项
        chrome_options = Options()
        chrome_options.add_argument("--no-sandbox")
        chrome_options.add_argument("--disable-dev-shm-usage")
        chrome_options.add_argument("--disable-gpu")
        chrome_options.add_argument("--window-size=1920,1080")
        chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
        
        # 指定chromedriver路径
        service = Service("/usr/bin/chromedriver")
        
        # 创建WebDriver实例
        print("正在初始化WebDriver...")
        driver = webdriver.Chrome(service=service, options=chrome_options)
        
        # 访问一个商品页面进行测试
        test_url = "https://www.amazon.com/Stanley-Quencher-Flowstate-Tumbler-Stainless/dp/B0DR9PNXX3"
        print(f"正在访问商品页面: {test_url}")
        driver.get(test_url)
        time.sleep(5)  # 等待页面加载
        
        # 滚动到页面底部，模拟用户行为
        print("滚动到页面底部...")
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(3)
        
        # 检查页面标题
        print(f"页面标题: {driver.title}")
        
        # 尝试定位页面底部的评论元素
        print("\n=== 页面底部评论元素测试 ===")
        review_selectors = [
            "#reviews-medley-footer",
            "[data-hook='reviews-medley-footer']",
            ".reviews-medley-footer",
            "#reviews-container",
            "[data-hook='review']",
            ".a-section.review.aok-relative",
            ".review",
            "[data-hook='top-reviews-widget']",
        ]
        
        for selector in review_selectors:
            try:
                elements = driver.find_elements(By.CSS_SELECTOR, selector)
                print(f"选择器 '{selector}': 找到 {len(elements)} 个元素")
                for i, element in enumerate(elements):
                    text = element.text.strip()
                    if text:
                        print(f"  元素 {i+1}: {text[:100]}...")
            except Exception as e:
                print(f"选择器 '{selector}' 出错: {e}")
        
        # 尝试获取底部评论区的评分信息
        print("\n=== 底部评论评分信息 ===")
        rating_selectors = [
            "#reviews-medley-footer .a-icon-alt",
            "[data-hook='rating-out-of-text']",
            ".averageStarRatingNumerical",
            ".a-popover-trigger .a-size-base",
        ]
        
        for selector in rating_selectors:
            try:
                elements = driver.find_elements(By.CSS_SELECTOR, selector)
                print(f"选择器 '{selector}': 找到 {len(elements)} 个元素")
                for i, element in enumerate(elements):
                    text = element.text.strip()
                    if text:
                        print(f"  元素 {i+1}: {text}")
            except Exception as e:
                print(f"选择器 '{selector}' 出错: {e}")
        
        # 尝试获取底部的几条评论
        print("\n=== 底部评论内容 ===")
        # 先滚动到评论区
        try:
            reviews_section = driver.find_element(By.CSS_SELECTOR, "#reviews-medley-footer")
            driver.execute_script("arguments[0].scrollIntoView();", reviews_section)
            time.sleep(2)
        except:
            print("无法定位到评论区")
        
        # 查找评论元素
        bottom_review_selectors = [
            "#reviews-medley-footer [data-hook='review']",
            "#reviews-medley-footer .review",
            "[data-hook='review']",
        ]
        
        for selector in bottom_review_selectors:
            try:
                review_elements = driver.find_elements(By.CSS_SELECTOR, selector)
                print(f"底部评论选择器 '{selector}': 找到 {len(review_elements)} 条评论")
                if review_elements:
                    # 显示前几条评论的标题
                    for i, review in enumerate(review_elements[:3]):
                        try:
                            title = review.find_element(By.CSS_SELECTOR, "[data-hook='review-title'] span").text
                            print(f"  评论 {i+1} 标题: {title}")
                        except:
                            try:
                                title = review.find_element(By.CSS_SELECTOR, ".review-title span").text
                                print(f"  评论 {i+1} 标题: {title}")
                            except:
                                print(f"  评论 {i+1}: 无法获取标题")
                    break
            except Exception as e:
                print(f"底部评论选择器 '{selector}' 出错: {e}")
        
        # 关闭浏览器
        input("按回车键关闭浏览器...")
        driver.quit()
        print("\n测试完成!")
        
    except Exception as e:
        print(f"测试过程中出现错误: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    test_product_page_reviews()